package sky.dao.Impl;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import sky.dao.UserDAO;
import sky.domain.Ticket;
import sky.domain.User;

/**
 * Created with IntelliJ IDEA.
 * User: Gauss
 * Date: 25.04.13
 * Time: 19:37
 * To change this template use File | Settings | File Templates.
 */
@Repository
public class UserDAOImpl implements UserDAO {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public User getUser(String username) {
        Query query = sessionFactory.getCurrentSession().createQuery("from User where name = :username");
        query.setParameter("username", username);
        User user = (User) query.uniqueResult();
        if (user != null) Hibernate.initialize(user.getCards());
        if (user != null) {
            Hibernate.initialize(user.getTickets());
        }
        return (User) query.uniqueResult();
    }

    @Override
    public void addUser(User user) {
        user.setRole("ROLE_USER");
        user.setChild(false);
        sessionFactory.getCurrentSession().save(user);
    }
}
